
package com.zdx.yswl.ui.activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.wifi.ScanResult;
import android.os.Environment;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jovision.Jni;
import com.zdx.yswl.R;
import com.zdx.yswl.ui.base.BaseActivity;
import com.zdx.yswl.ui.bean.Channel;
import com.zdx.yswl.ui.bean.Device;
import com.zdx.yswl.ui.tool.AppConsts;
import com.zdx.yswl.ui.tool.Consts;
import com.zdx.yswl.ui.tool.JVNetConst;
import com.zdx.yswl.ui.tool.LsitWifiAdapter;
import com.zdx.yswl.ui.tool.MyAudio;
import com.zdx.yswl.ui.tool.PlayUtil;
import com.zdx.yswl.ui.tool.SqliteDBHelper;
import com.zdx.yswl.ui.tool.WifiAdmin;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PlayActivity extends BaseActivity
{

    private static final String TAG = "PlayActivity";
    private static final int DISMISS_DIALOG = 0x01;

    private SurfaceView playSurface;// 视频播放view
    private TextView linkState;// 连接状态
    private SurfaceHolder holder;
    private Button audioListening;// 音频监听功能

    /********** 单向对讲功能，录像，切换码流 远程回放 **********/
    private LinearLayout voiceCall, record, changeStream, checkRemote;
    private TextView voiceviewText, recordText;
    private ImageView imgBack;
    private ImageView imgExit;
    private int current;
    private AudioManager mAudioManager;

    /********** wifi相关 **********/
    private ListView wifiList;
    private ArrayList<ScanResult> wifiInfoList;
    private ArrayList<ScanResult> wifiInfoListTemp;
    private LsitWifiAdapter listWifiAdapter;
    private ImageView wifiSelector;
    private Boolean isWifiSet; // wifi列表是否打开
    private String ssid;
    private Boolean isWifiSetSuccess; // 配置成功
    private String devicename;

    private Button wifiSet,throughAgreementBtn, osdFunc,
            modifypass; // 无线配置,透传协议，隐藏显示osd，修改用户密码
    public static Channel connectChannel;
    private boolean apConnect = false;// 是否Ap直连设备

    /**** 对讲用 ******/
    public static MyAudio playAudio;
    protected RelativeLayout voiceTip;// 单向对讲提示
    protected boolean realStop = false;
    public static boolean AUDIO_SINGLE = false;// 单向对讲标志
    public static boolean VOICECALL_LONG_CLICK = false;// 语音喊话flag长按状态,长按发送数据
    public static boolean VOICECALLING = false;// 对讲功能已经开启
    public static boolean GATHER_AUDIO_DATA = true;// 是否采集音频数据

    public static boolean showingOsd = true;// 是否显示着osd true显示 false没显示

    /**** 码流切换 ******/
    private PopupWindow streamPopWindow;
    private Button hdBtn;
    private Button sdBtn;
    private Button fluentBtn;

    /**** 无线配置 ******/
    private RelativeLayout wifiSetLayout;
    private EditText wifiName;
    private EditText wifiPass;
    private Button saveSet;
    private WifiAdmin wifiAdmin;

    /**
     * 修改密码输入框
     */
    private int power;
    public String descript = "";
    public String params;

    private EditText userET;
    private EditText pswET;

    /**
     * 视频连接
     * 
     * @param device
     * @param channel
     * @param surface
     * @return
     */
    private int connect(Device device, Channel channel, Surface surface)
    {
        int result = -1;
        if (null != device && null != channel) {
            if ("".equalsIgnoreCase(device.getIp()) || 0 == device.getPort())
            {
                // 无ip和端口走云视通连接
                result = Jni.connect(channel.getIndex(), channel.getChannel(), device.getIp(),
                        device.getPort(), "admin", "123", device.getNo(), device.getGid(),
                        true, 1, true, JVNetConst.TYPE_3GMO_UDP, surface, false, false,
                        apConnect, false, null);
            }
            else
            {
                // 有Ip用ip连接，云视通号字段需要传-1，否则仍然走的云视通连接
                result = Jni.connect(channel.getIndex(), channel.getChannel(), device.getIp(),
                        device.getPort(), device.getUser(), device.getPwd(), -1,
                        device.getGid(), true, 1, true, JVNetConst.TYPE_3GMO_UDP,
                        surface, false, false, apConnect, false, null);
            }
        }
        return result;
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if(connectChannel != null && connectChannel.isConnected())
        {
            Jni.disconnect(DevMainActivity.channelIndex);
            connectChannel.setConnected(false);
            connectChannel.setPaused(false);
        }
    }

    @Override
    public void onNotify(int what, int arg1, int arg2, Object obj)
    {
        handler.sendMessage(handler.obtainMessage(what, arg1, arg2, obj));
    }

    @Override
    public void onHandler(int what, int arg1, int arg2, Object obj)
    {
        switch (what)
        {
            case DISMISS_DIALOG: // 1
            {
                linkState.setVisibility(View.GONE);
                break;
            }

            case AppConsts.CALL_NORMAL_DATA: // 162
            {
                connectChannel.setConnected(true);
                connectChannel.setPaused(false);
                handler.sendEmptyMessage(DISMISS_DIALOG);
                try
                {
                    JSONObject jobj;
                    jobj = new JSONObject(obj.toString());
                    int type = jobj.optInt("device_type");
                    if (null != jobj)
                    {
                        connectChannel.getParent().setType(type);
                        connectChannel.getParent()
                                .setJFH(jobj.optBoolean("is_jfh"));
                        connectChannel.getParent().set05(jobj.optBoolean("is05"));
                        connectChannel.setAudioType(jobj.getInt("audio_type"));
                        connectChannel.setAudioByte(jobj.getInt("audio_bit"));
                        connectChannel.setAudioEncType(jobj.getInt("audio_enc_type"));
                        connectChannel.setSingleVoice(true);
                        if (8 == connectChannel.getAudioByte()
                                && AppConsts.DEVICE_TYPE_DVR == type)
                        {
                            connectChannel.setSupportVoice(false);
                        }
                        else
                        {
                            connectChannel.setSupportVoice(true);
                        }

                        Jni.sendBytes(arg1, JVNetConst.JVN_REQ_TEXT, new byte[0], 8);
                    }
                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                }

                break;
            }

            case Consts.CALL_TEXT_DATA: //165
            {
                switch (arg2)
                {
                    case JVNetConst.JVN_RSP_TEXTACCEPT://82 同意文本聊天
                        try
                        {
                            Thread.sleep(50);
                        }
                        catch (InterruptedException e1)
                        {
                            e1.printStackTrace();
                        }
                        // 获取主控码流信息请求
                        Jni.sendTextData(arg1, JVNetConst.JVN_RSP_TEXTDATA, 8, JVNetConst.JVN_STREAM_INFO);
                        // 2015-4-22 获取设备用户名密码
                        Jni.sendSuperBytes(arg1, JVNetConst.JVN_RSP_TEXTDATA, true, Consts.RC_EX_ACCOUNT, Consts.EX_ACCOUNT_REFRESH, Consts.POWER_ADMIN, 0, 0, new byte[0], 0);
                        connectChannel.setAgreeTextData(true);
                        break;

                    case JVNetConst.JVN_CMD_TEXTSTOP://83 不同意文本聊天
                        connectChannel.setAgreeTextData(false);
                        break;

                    case JVNetConst.JVN_RSP_TEXTDATA://81 文本数据
                        String allStr = obj.toString();
                        Log.e(TAG, "文本数据--" + allStr);
                        try
                        {
                            JSONObject dataObj = new JSONObject(allStr);

                            switch (dataObj.getInt("flag"))
                            {
                                // 远程配置请求，获取到配置文本数据
                                case JVNetConst.JVN_GET_USERINFO:  // 20
                                {
                                    int extend_type = dataObj.getInt("extend_type");
                                    if (Consts.EX_ACCOUNT_REFRESH == extend_type)
                                    {
                                        String InfoJSON = dataObj.getString("extend_msg");
                                        InfoJSON = InfoJSON.replaceAll("ID", "+ID");
                                        String[] array = InfoJSON.split("\\+");
                                        for (int i = 1; i < array.length; i++) {
                                            if (null != array[i] && !array[i].equals("")) {
                                                HashMap<String, String> idomap = new HashMap<String, String>();
                                                idomap = genMsgMap(array[i]);
                                                int getPower = Integer.parseInt(idomap.get("POWER"));
                                                String getDescript = idomap.get("DESCRIPT");
                                                if (idomap.get("ID").equals("admin")
                                                        && 4 == (0x04 & getPower)) {
//                                                    Log.e("power-", "" + power);
                                                    power = getPower;
                                                    if (null == getDescript
                                                            || "".equals(getDescript)) {
                                                        descript = "";
                                                    } else {
                                                        descript = getDescript;
                                                    }

                                                }
                                            }
                                        }
                                    }
                                    else if (Consts.EX_ACCOUNT_MODIFY == extend_type)  // 修改成功
                                    {
                                        showTextToast(R.string.modifypass_success);
                                    }
                                    break;
                                }

                                case JVNetConst.JVN_REQ_CALLBACK: //0
                                {
                                    // CALL_TEXT_DATA: 165, 0, 81,
                                    // {"extend_arg1":0,"extend_arg2":0,"extend_arg3":9,"extend_type":39,"flag":0,"msg":"abc123456","packet_count":18,"packet_id":0,"packet_length":0,"packet_type":6}
                                    int extendType = dataObj.getInt("extend_type");
                                    if (extendType == Consts.EX_COMTRANS_RESV)
                                    {
                                        String msg = dataObj.getString("msg"); // 透传回调,串口收的回调
                                        // Log.e(TAG, "透传回调数据--" + msg);
                                    }
                                    break;
                                }

                                case JVNetConst.JVN_REMOTE_SETTING: //1
                                {
                                    break;
                                }

                                case JVNetConst.JVN_WIFI_INFO: //2 AP,WIFI热点请求
                                    break;

                                case JVNetConst.JVN_STREAM_INFO: //3  码流配置请求
                                    // Log.e(TAG, "JVN_STREAM_INFO:TEXT_DATA: " + what + ", " + arg1 + ", " + arg2 + ", " + obj);
                                    String streamJSON = dataObj.getString("msg");
                                    HashMap<String, String> streamMap = genMsgMap(streamJSON);
                                    if (null != streamMap.get("MobileQuality")
                                            && !"".equalsIgnoreCase(streamMap
                                                    .get("MobileQuality"))) {
                                        // Log.v(TAG, "MobileQuality=" + streamMap.get("MobileQuality"));
                                        int mobileQuality = Integer.parseInt(streamMap.get("MobileQuality"));
                                        if (1 == mobileQuality) {
                                            hdBtn.setTextColor(Color.BLUE);
                                            sdBtn.setTextColor(Color.BLACK);
                                            fluentBtn.setTextColor(Color.BLACK);
                                        }
                                        else if (2 == mobileQuality)
                                        {
                                            hdBtn.setTextColor(Color.BLACK);
                                            sdBtn.setTextColor(Color.BLUE);
                                            fluentBtn.setTextColor(Color.BLACK);
                                        }
                                        else if (3 == mobileQuality)
                                        {
                                            hdBtn.setTextColor(Color.BLACK);
                                            sdBtn.setTextColor(Color.BLACK);
                                            fluentBtn.setTextColor(Color.BLUE);
                                        }

                                    }

                                    if (null != streamMap.get("nPosition")
                                            && "4".equalsIgnoreCase(streamMap
                                                    .get("nPosition"))
                                            && null != streamMap.get("nTimePosition")
                                            && "4".equalsIgnoreCase(streamMap
                                                    .get("nTimePosition"))) {

                                        showingOsd = false;
                                        osdFunc.setText(R.string.show_osd);
                                    }
                                    else
                                    {
                                        osdFunc.setText(R.string.dismiss_osd);
                                    }
                                    break;

                                /** wifi配置成功和不成功时的处理 **/
                                case JVNetConst.EX_WIFI_AP_CONFIG:  //11，新wifi配置流程
                                    if (0 == dataObj.getInt("result"))  // 配置成功
                                    {
                                        showTextToast(R.string.set_success);
                                        isWifiSetSuccess = true;
                                        if(ssid.length() >= 8 && ssid.substring(1, 8).equals("IPC-H-B"))
                                        {
                                            devicename = ssid.substring(7, ssid.length() - 1);
                                        }
                                    }
                                    else  // 配置失败
                                    {
                                        dismissDialog();
                                        showTextToast(R.string.set_failed);
                                    }
                                    break;
                                default:
                                    break;
                            }

                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                        break;
                }
                break;
            }

            case AppConsts.STOP_AUDIO_GATHER: //8 停止采集音频数据
            {
                GATHER_AUDIO_DATA = false;
                break;
            }

            case AppConsts.START_AUDIO_GATHER: //9 开始采集音频数据
            {
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, current, 0);
                // mic关闭就不能从外面接受声音
                mAudioManager.setMicrophoneMute(true);
                GATHER_AUDIO_DATA = true;
                break;
            }

            case AppConsts.CALL_PLAY_AUDIO: //173 音频数据
            {
                if (!GATHER_AUDIO_DATA)
                {
                    break;
                }

                if (null != obj && null != playAudio)
                {
                    if (AUDIO_SINGLE)
                    {
                        // 单向对讲长按才发送语音数据，长按时为true
                        if (VOICECALL_LONG_CLICK)
                        {
                            // 长按时只发送语音，不接收语音
                        }
                        else
                        {
                            byte[] data = (byte[]) obj;
                            // audioQueue.offer(data);
                            // [Neo] 将音频填入缓存队列
                            playAudio.put(data);
                        }
                    }
                    else
                    {
                        // 双向对讲直接播放设备传过来的语音
                        byte[] data = (byte[]) obj;
                        // audioQueue.offer(data);
                        // [Neo] 将音频填入缓存队列
                        playAudio.put(data);
                    }
                }
                break;
            }

            case Consts.CALL_CHAT_DATA: //164
            {
                dismissDialog();
                switch (arg2) // 语音数据
                {
                    case JVNetConst.JVN_RSP_CHATDATA: //65
                    {
                        break;
                    }

                    case JVNetConst.JVN_RSP_CHATACCEPT: //66 同意语音请求
                    {
                        dismissDialog();
                        voiceviewText.setText(R.string.voice_send);
                        showTextToast(R.string.voice_tips2);

                        if (AppConsts.JAE_ENCODER_G729 == connectChannel
                                .getAudioEncType())
                        {
                            playAudio.startPlay(16, true); // 开启语音对讲
                            playAudio.startRec(connectChannel.getIndex(),
                                    connectChannel.getAudioEncType(), 16,
                                    connectChannel.getAudioBlock(), true);
                        }
                        else
                        {
                            playAudio.startPlay(connectChannel.getAudioByte(), true);  // 开启语音对讲
                            playAudio.startRec(connectChannel.getIndex(),
                                    connectChannel.getAudioEncType(),
                                    connectChannel.getAudioByte(),
                                    connectChannel.getAudioBlock(), true);
                        }
                        connectChannel.setVoiceCall(true);
                        VOICECALLING = true;
                        break;
                    }

                    case JVNetConst.JVN_CMD_CHATSTOP: //67 暂停语音聊天
                    {
                        if (realStop)
                        {
                            realStop = false;
                        }
                        else
                        {
                            showTextToast(R.string.has_calling);
                        }
                        break;
                    }
                }
                break;
            }

            case AppConsts.CALL_CONNECT_CHANGE: // 161
            {
                dismissDialog();
                if(isWifiSetSuccess)
                {
                    Intent intent = new Intent(PlayActivity.this, DevMainActivity.class);
                    intent.putExtra("isWifiSetSuccess", isWifiSetSuccess);
                    Log.e("devicename", devicename);
                    intent.putExtra("devicename", devicename);
                    setResult(Consts.RECODE, intent);
                    isWifiSetSuccess = false;
                    finish();
                }
                switch (arg2) // 连接结果
                {
                    // 1 -- 连接成功
                    case JVNetConst.CONNECT_OK: //1
                    {
                        connectChannel.setConnected(true);
                        connectChannel.setPaused(false);
                        linkState.setVisibility(View.GONE);
                        // 视频连接成功，如果连接的用户名密码是默认的建议用户修改管理员密码
                        if (AppConsts.DEFAULT_USER.equalsIgnoreCase(DevMainActivity.device.getUser())
                                && AppConsts.DEFAULT_PWD.equalsIgnoreCase(DevMainActivity.device
                                        .getPwd()))
                        {
                            showTextToast(R.string.edit_user_pass_tips1);
                        }
                        break;
                    }
                    // 2 -- 断开连接成功
                    case JVNetConst.DISCONNECT_OK: //2
                    {
                        connectChannel.setConnected(false);
                        connectChannel.setPaused(false);
                        JSONObject connectObj;
                        try {
                            connectObj = new JSONObject(obj.toString());
                            String errorMsg = connectObj.getString("msg");
                            linkState.setVisibility(View.VISIBLE);
                            linkState.setText(errorMsg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        break;
                    }
                    // 4 -- 连接失败
                    case JVNetConst.CONNECT_FAILED: //3
                    {
                        try {
                            JSONObject connectObj = new JSONObject(obj.toString());
                            String errorMsg = connectObj.getString("msg");
                            if ("password is wrong!".equalsIgnoreCase(errorMsg)
                                    || "pass word is wrong!".equalsIgnoreCase(errorMsg)) {// 密码错误时提示身份验证失败
                                linkState.setText(getResources()
                                        .getString(R.string.connfailed_auth));

                            } else if ("channel is not open!"
                                    .equalsIgnoreCase(errorMsg)) {// 无该通道服务
                                linkState.setText(getResources().getString(
                                        R.string.connfailed_channel_notopen));
                            } else if ("connect type invalid!"
                                    .equalsIgnoreCase(errorMsg)) {// 连接类型无效
                                linkState.setText(getResources().getString(
                                        R.string.connfailed_type_invalid));
                            } else if ("client count limit!".equalsIgnoreCase(errorMsg)) {// 超过主控最大连接限制
                                linkState.setText(getResources().getString(
                                        R.string.connfailed_maxcount));
                            } else if ("connect timeout!".equalsIgnoreCase(errorMsg)) {//
                                linkState.setText(getResources().getString(
                                        R.string.connfailed_timeout));
                            } else if ("check password timeout!"
                                    .equalsIgnoreCase(errorMsg)) {// 验证密码超时
                                linkState.setText(getResources().getString(
                                        R.string.connfailed_checkpass_timout));
                            } else {// "Connect failed!"
                                linkState
                                        .setText(getResources().getString(R.string.connect_failed));
                            }
                        }
                        catch (JSONException e)
                        {
                            e.printStackTrace();
                            linkState.setText(getResources().getString(R.string.closed));
                        }
                        connectChannel.setConnected(false);
                        connectChannel.setPaused(false);
                        linkState.setVisibility(View.VISIBLE);
                        break;
                    }
                    // 6 -- 连接异常断开
                    case JVNetConst.ABNORMAL_DISCONNECT: //4
                    {
                        connectChannel.setConnected(false);
                        connectChannel.setPaused(false);
                        linkState.setVisibility(View.VISIBLE);
                        linkState.setText(getResources().getString(R.string.abnormal_closed1));
                        break;
                    }
                    // 7 -- 服务停止连接，连接断开
                    case JVNetConst.SERVICE_STOP: //5
                    {
                        connectChannel.setConnected(false);
                        connectChannel.setPaused(false);
                        linkState.setVisibility(View.VISIBLE);
                        linkState.setText(getResources().getString(R.string.abnormal_closed2));
                        break;
                    }
                    // 3 -- 不必要重复连接
                    case JVNetConst.NO_RECONNECT: //6
                    {
                        connectChannel.setConnected(false);
                        connectChannel.setPaused(false);
                        linkState.setVisibility(View.VISIBLE);
                        linkState.setText(getResources().getString(R.string.abnormal_closed3));
                        break;
                    }
                    // 5 -- 没有连接
                    case JVNetConst.NO_CONNECT: //7
                    {
                        connectChannel.setConnected(false);
                        connectChannel.setPaused(false);
                        linkState.setVisibility(View.VISIBLE);
                        linkState.setText(getResources().getString(R.string.abnormal_closed4));
                        break;
                    }
                    // 8 -- 断开连接失败
                    case JVNetConst.DISCONNECT_FAILED: //8
                    {
                        connectChannel.setConnected(false);
                        connectChannel.setPaused(false);
                        linkState.setVisibility(View.VISIBLE);
                        linkState.setText(getResources().getString(R.string.abnormal_closed5));
                        break;
                    }

                    // 9 -- 其他错误
                    case JVNetConst.OHTER_ERROR: //9
                    {
                        connectChannel.setConnected(false);
                        connectChannel.setPaused(false);
                        linkState.setVisibility(View.VISIBLE);
                        linkState.setText("其他错误");
                        break;
                    }
                }
            }
        }
    }

    @Override
    protected void initSettings()
    {
        playAudio = MyAudio.getIntance(AppConsts.PLAY_AUDIO_WHAT, PlayActivity.this, 8000);
        mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        current = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM);

        apConnect = getIntent().getBooleanExtra("APConnect", false);

        wifiAdmin = new WifiAdmin(PlayActivity.this);
        wifiInfoList = (ArrayList)wifiAdmin.getWifiList();
        wifiInfoListTemp = new ArrayList<ScanResult>();
    }

    @Override
    protected void initUi()
    {
        // 获取当前音量
        mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        current = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM );

        setContentView(R.layout.activity_play);
        playSurface = (SurfaceView) findViewById(R.id.playsurface);
        linkState = (TextView) findViewById(R.id.linkstate);
        linkState.setTextColor(Color.GREEN);
        audioListening = (Button) findViewById(R.id.audiolistener);

        // 由Button改为LinearLayout
        voiceCall = (LinearLayout) findViewById(R.id.voicecall);
        record = (LinearLayout) findViewById(R.id.record);
        changeStream = (LinearLayout) findViewById(R.id.changestream);
        checkRemote = (LinearLayout) findViewById(R.id.checkremote);
        voiceviewText = (TextView) findViewById(R.id.voicecallText);
        recordText = (TextView)findViewById(R.id.recordText);

        // imgBack
        imgBack = (ImageView)findViewById(R.id.imgBack);
        imgBack.setOnClickListener(myOnClickListener);

        // imgExit
        imgExit = (ImageView)findViewById(R.id.imgExit);
        imgExit.setOnClickListener(myOnClickListener);

        // wifiList
        wifiList = (ListView)findViewById(R.id.wifi_list);
        wifiSelector = (ImageView)findViewById(R.id.wifiSelector);
        wifiSelector.setOnClickListener(myOnClickListener);

        //获取Wifi列表
        isWifiSet = new Boolean(false);
        String wifiNameTemp;
        for(int i = 0; i < wifiInfoList.size(); i++)
        {
            wifiNameTemp = wifiInfoList.get(i).SSID;
            if (wifiNameTemp.length() >= 7 && wifiNameTemp.toString().substring(0, 7).equals("IPC-H-B"))
            {
                // Do Nothing
            }
            else
            {
                wifiInfoListTemp.add(wifiInfoList.get(i));
            }
        }
        listWifiAdapter = new LsitWifiAdapter(PlayActivity.this, wifiInfoListTemp);
        wifiList.setAdapter(listWifiAdapter);
        wifiList.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
            {
                wifiName.setText(wifiInfoListTemp.get(i).SSID);
                wifiList.setVisibility(View.GONE);
            }
        });

        // wifi配置
        wifiSet = (Button) findViewById(R.id.wifiset);
        wifiSetLayout = (RelativeLayout) findViewById(R.id.wifisetlayout);
        wifiName = (EditText) wifiSetLayout.findViewById(R.id.wifiname);
        wifiPass = (EditText) wifiSetLayout.findViewById(R.id.wifipass);
        saveSet = (Button) wifiSetLayout.findViewById(R.id.saveset);
        saveSet.setOnClickListener(myOnClickListener);

        throughAgreementBtn = (Button) findViewById(R.id.through_agreement);
        osdFunc = (Button) findViewById(R.id.osd_visibility);
        modifypass = (Button) findViewById(R.id.modifypass);
        throughAgreementBtn.setOnClickListener(myOnClickListener);
        osdFunc.setOnClickListener(myOnClickListener);
        modifypass.setOnClickListener(myOnClickListener);

        voiceTip = (RelativeLayout) findViewById(R.id.voicetip);
        audioListening.setOnClickListener(myOnClickListener);
        voiceCall.setOnClickListener(myOnClickListener);
        record.setOnClickListener(myOnClickListener);
        changeStream.setOnClickListener(myOnClickListener);
        checkRemote.setOnClickListener(myOnClickListener);
        wifiSet.setOnClickListener(myOnClickListener);

        holder = playSurface.getHolder();
        initStreamPopWindowView();
        hdBtn.setOnClickListener(myOnClickListener);
        sdBtn.setOnClickListener(myOnClickListener);
        fluentBtn.setOnClickListener(myOnClickListener);

        holder.addCallback(new SurfaceHolder.Callback()
        {
            @Override
            public void surfaceDestroyed(SurfaceHolder holder)
            {
            }

            @Override
            public void surfaceCreated(SurfaceHolder holder)
            {
                linkState.setVisibility(View.VISIBLE);
                linkState.setText(R.string.connectting);

                connectChannel = DevMainActivity.device.getChannelList().get(DevMainActivity.channelIndex);
                if(!connectChannel.isConnected())
                {
                    connectChannel.setParent(DevMainActivity.device);
                    connect(DevMainActivity.device, connectChannel, holder.getSurface());
                }
                else if(connectChannel.isConnected() && connectChannel.isPaused())
                {
                    boolean result = Jni.sendBytes(connectChannel.getIndex(), JVNetConst.JVN_CMD_VIDEO, new byte[0], 8);
                    connectChannel.setPaused(false);
                    //                    Log.v(TAG, "onResume=" + result);

                    if(result)
                    {
                        boolean resumeRes = Jni.resume(connectChannel.getIndex(), holder.getSurface());
                        //                        Log.v(TAG, "JNI-Play-Resume=" + resumeRes);
                        if(resumeRes)
                        {
                            linkState.setVisibility(View.GONE);
                        }
                    }
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
            {
            }
        });

        voiceCall.setOnClickListener(myOnClickListener);
        voiceCall.setOnTouchListener(callOnTouchListener);
        voiceCall.setOnLongClickListener(callOnLongClickListener);

        isWifiSetSuccess = new Boolean(false);
    }

    /**
     * 开始远程回放方法
     */
    public void startRemote()
    {
        if (null != connectChannel && connectChannel.isConnected())
        {
            Intent remoteIntent = new Intent();
            remoteIntent.setClass(PlayActivity.this, RemoteListActivity.class);
            remoteIntent.putExtra("IndexOfChannel", connectChannel.getIndex());
            remoteIntent.putExtra("ChannelOfChannel",
                    connectChannel.getChannel());
            remoteIntent.putExtra("is05", connectChannel.getParent().is05());
            remoteIntent.putExtra("DeviceType", connectChannel.getParent()
                    .getType());
            remoteIntent.putExtra("isJFH", connectChannel.getParent().isJFH());
            PlayActivity.this.startActivityForResult(remoteIntent, Consts.RECODE1);
        }
        else
        {
            Toast.makeText(PlayActivity.this, R.string.not_connected, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void saveSettings()
    {

    }

    @Override
    protected void freeMe()
    {

    }

    @Override
    protected void onStop()
    {
        super.onStop();
        Log.e(TAG, "onStop");
//        if (null != connectChannel && connectChannel.isConnected()
//            && !connectChannel.isPaused())
//        {
//            connectChannel.setPaused(true);
//            boolean result =
//                    Jni.sendBytes(connectChannel.getIndex(),
//                                  JVNetConst.JVN_CMD_VIDEOPAUSE, new byte[0], 8);
//        }
//        boolean pauseRes = Jni.pause(connectChannel.getIndex());
//
//        Jni.disconnect(DevMainActivity.channelIndex);
//        connectChannel.setConnected(false);
//        connectChannel.setPaused(false);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        if (null != connectChannel && connectChannel.isConnected()
                && !connectChannel.isPaused())
        {
            connectChannel.setPaused(true);
            boolean result = Jni.sendBytes(connectChannel.getIndex(), JVNetConst.JVN_CMD_VIDEOPAUSE, new byte[0], 8);
            boolean pauseRes = Jni.pause(connectChannel.getIndex());
            
            // 停止语音对话
            voiceviewText.setText(R.string.voicecall); // 停止语音对讲
            stopVoiceCall(connectChannel.getIndex());
            connectChannel.setVoiceCall(false);
            realStop = true;
            VOICECALLING = false;
        }

        Log.e(TAG, "onPause");

        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, current, 0);
    }

    @Override
    protected void onStart()
    {
        super.onStart();
    }

    @Override
    public void onBackPressed()
    {
        super.onBackPressed();
        // 除去progressDialog
        dismissDialog();
        // 保存当前录像视频
        if(connectChannel.isConnected())
        {
            Jni.stopRecord();
            recordText.setText(R.string.record);
            
            // 停止语音对话
            voiceviewText.setText(R.string.voicecall); // 停止语音对讲
            stopVoiceCall(connectChannel.getIndex());
            connectChannel.setVoiceCall(false);
            realStop = true;
            VOICECALLING = false;
            // 断开链接
            
            Jni.disconnect(DevMainActivity.channelIndex);
        }
    }

    /**
     * 云台按钮事件
     */
    ImageView.OnClickListener imageOnClickListener = new ImageView.OnClickListener() {
        @Override
        public void onClick(View arg0) {
        }
    };


    private OnClickListener myOnClickListener = new OnClickListener()
    {

        @Override
        public void onClick(View view)
        {
            boolean isLisening = PlayUtil
                    .isPlayAudio(connectChannel.getIndex());

            switch (view.getId())
            {
                case R.id.wifiSelector:
                    if(isWifiSet == false)
                    {
                        wifiList.setVisibility(View.VISIBLE);
                        isWifiSet = true;
                    }
                    else
                    {
                        wifiList.setVisibility(View.GONE);
                        isWifiSet = false;
                    }
                    break;

                case R.id.imgBack:
                    // 保存当前录像视频
                    Jni.stopRecord();
                    recordText.setText(R.string.record);
                    finish();
                    break;

                case R.id.imgExit:
                    // 恢复无线配置为可点击
                    wifiSet.setEnabled(true);
                    wifiSetLayout.setVisibility(View.GONE);
                    break;

                case R.id.modifypass:
                    // TODO
                    if (connectChannel.isConnected())
                    {
                        // 视频连接成功后才可以修改设备的用户名密码
                        showTextToast(R.string.edit_user_pass_tips2);
                    }
                    break;
                case R.id.osd_visibility:
                {

                    if (showingOsd)
                    {
                        showingOsd = false;
                        osdFunc.setText(R.string.show_osd);
                        // 隐藏OSD
                        String dismiss = "[ALL];nPosition=4;nTimePosition=4 ;";

                        Jni.sendSuperBytes(connectChannel.getIndex(), JVNetConst.JVN_RSP_TEXTDATA, false, dismiss.getBytes().length, JVNetConst.RC_SETPARAM, 0, 0, 0, dismiss.getBytes(), dismiss.getBytes().length);

                    }
                    else
                    {
                        showingOsd = true;
                        osdFunc.setText(R.string.dismiss_osd);
                        // 显示OSD,1,2 的值代表
                        String show = "[ALL];nPosition=1;nTimePosition=2 ;";

                        Jni.sendSuperBytes(connectChannel.getIndex(), JVNetConst.JVN_RSP_TEXTDATA, false, show.getBytes().length, JVNetConst.RC_SETPARAM, 0, 0, 0, show.getBytes(), show.getBytes().length);

                    }

                    break;
                }
                case R.id.audiolistener:
                {
                    // 音频监听
                    if (connectChannel.isVoiceCall())
                    {
                        // 对讲时不允许开监听
                        break;
                    }
                    if (isLisening)
                    {
                        // 正在监听
                        audioListening.setText(R.string.audiolistener);
                        stopAudio(connectChannel.getIndex());
                    }
                    else
                    {
                        audioListening.setText(R.string.audiolistening);
                        startAudio(connectChannel.getIndex(), connectChannel.getAudioByte());
                    }
                    break;
                }
                
                /** 语音对讲按钮 **/
                case R.id.voicecall:
                {
                    if(connectChannel.isConnected())
                    {
                        // 恢复无线配置按钮为可点击
                        wifiSet.setEnabled(true);
                        // 隐藏无线配置窗口
                        wifiSetLayout.setVisibility(View.GONE);
                        // 隐藏码流配置
                        if(streamPopWindow != null)
                        {
                            streamPopWindow.dismiss();
                        }
                        // 语音对讲
                        if(isLisening)
                        {
                            // 正在监听,先停止监听
                            audioListening.setText(R.string.audiolistener);
                            stopAudio(connectChannel.getIndex());
                        }
                        if(AppConsts.JAE_ENCODER_G729 != connectChannel.getAudioEncType() && 8 == connectChannel.getAudioByte())
                        {
                            showTextToast("不支持此设备");
                            return;
                        }
                        else
                        {
                            if(connectChannel.isVoiceCall())
                            {
                                voiceviewText.setText(R.string.voicecall);
                                stopVoiceCall(connectChannel.getIndex());
                                connectChannel.setVoiceCall(false);
                                realStop = true;
                                VOICECALLING = false;
                            }
                            else
                            {
                                stopVoiceCall(connectChannel.getIndex());
                                AUDIO_SINGLE = connectChannel.isSingleVoice();
                                createDialog("请稍等...", false, true);
                                startVoiceCall(connectChannel.getIndex(), connectChannel);
                                connectChannel.setVoiceCall(true);
                                realStop = false;
                                VOICECALLING = true;
                            }
                        }
                    }
                    else
                    {
                        showTextToast("视频未连接");
                    }
                    break;
                }

                /** 录像按钮 **/
                case R.id.record:
                {
                    // 停止语音对话
                    voiceviewText.setText(R.string.voicecall);
                    stopVoiceCall(connectChannel.getIndex());
                    connectChannel.setVoiceCall(false);
                    realStop = true;
                    VOICECALLING = false;
                    // 恢复无线配置按钮为可点击
                    wifiSet.setEnabled(true);
                    // 隐藏无线配置窗口
                    wifiSetLayout.setVisibility(View.GONE);
                    // 隐藏码流选择悬浮窗口
                    if(streamPopWindow != null)
                    {
                        streamPopWindow.dismiss();
                    }
                    // 录像
                    if(connectChannel.isConnected())
                    {
                        String savePath = Environment.getExternalStorageDirectory().getPath() + File.separator + "sdkvideo";
                        File saveFile = new File(savePath);
                        if(!saveFile.exists())
                        {
                            saveFile.mkdir();
                        }
                        if(Jni.checkRecord(connectChannel.getIndex()))
                        {
                            // 停止录像
                            Jni.stopRecord();
                            showTextToast(getResources().getString(R.string.record_savedas) + savePath);
                            recordText.setText(R.string.record);
                        }
                        else
                        {
                            Jni.startRecord(connectChannel.getIndex(), savePath + File.separator + System.currentTimeMillis() + ".mp4", true, true);
                            recordText.setText(R.string.recording);
                        }
                    }
                    else
                    {
                        showTextToast("视频未连接");
                    }
                    break;
                }

                /** 码流选择按钮 **/
                case R.id.changestream:
                {
                    // 停止语音对话
                    voiceviewText.setText(R.string.voicecall);
                    stopVoiceCall(connectChannel.getIndex());
                    connectChannel.setVoiceCall(false);
                    realStop = true;
                    VOICECALLING = false;
                    // 恢复无线配置按钮为可点击
                    wifiSet.setEnabled(true);
                    // 隐藏无线配置窗口
                    wifiSetLayout.setVisibility(View.GONE);
                    // 切换码流,如果录像的过程中切换码流，录像会自动停止
                    Jni.stopRecord(); // 保存当前录像视频
                    recordText.setText(R.string.record);
                    if(connectChannel.isConnected())
                    {
                        if(null == streamPopWindow)
                        {
                            initStreamPopWindowView();
                            streamPopWindow.showAsDropDown(changeStream);
                        } else
                        {
                            if(streamPopWindow.isShowing())
                            {
                                streamPopWindow.dismiss();
                            } else
                            {
                                streamPopWindow.showAsDropDown(changeStream);
                            }

                        }
                    }
                    else
                    {
                        showTextToast("视频未连接");
                    }
                    break;
                }

                /** 远程回放按钮 **/
                case R.id.checkremote:
                {
                    // 停止语音对话
                    voiceviewText.setText(R.string.voicecall);
                    stopVoiceCall(connectChannel.getIndex());
                    connectChannel.setVoiceCall(false);
                    realStop = true;
                    VOICECALLING = false;

                    Jni.stopRecord(); // 保存当前录像视频
                    recordText.setText(R.string.record);

                    wifiSet.setEnabled(true); // 恢复无线配置按钮为可点击

                    wifiSetLayout.setVisibility(View.GONE); // 隐藏无线配置窗口

                    if(streamPopWindow != null)  // 隐藏码流悬着悬浮窗口
                    {
                        streamPopWindow.dismiss();
                    }

                    startRemote(); // 远程回放检索
                    break;
                }

                /**无线配置**/
                case R.id.wifiset:
                {
                    if(streamPopWindow != null)
                    {
                        streamPopWindow.dismiss(); // 隐藏码流选择窗口
                    }

                    if(connectChannel.isConnected())
                    {
                        wifiSet.setEnabled(false);   // 禁止无线配置按钮可以点击，在Wifi选择完成后才可以点击
                        ssid = wifiAdmin.getSSID();
                        if(View.VISIBLE == wifiSetLayout.getVisibility())
                        {
                            wifiSetLayout.setVisibility(View.GONE);
                            wifiList.setVisibility(View.GONE); // ytLayout.setVisibility(View.VISIBLE);
                        } else
                        {
                            wifiSetLayout.setVisibility(View.VISIBLE);
                            wifiList.setVisibility(View.GONE); // ytLayout.setVisibility(View.GONE);
                        }
                    }
                    else
                    {
                        showTextToast("视频未连接");
                    }
                    break;
                }

                /** 透传协议 **/
                case R.id.through_agreement:
                {
                    String params = "ff 01 02 03 f0";
                    byte[] data = params.getBytes();
                    Jni.sendSuperBytes(connectChannel.getIndex(), JVNetConst.JVN_RSP_TEXTDATA, true, Consts.RC_EX_COMTRANS, Consts.EX_COMTRANS_SEND, 0, 0, data.length, data, data.length);// 前进
                    break;
                }

                case R.id.hd: // 高清
                {
                    Jni.sendString(connectChannel.getIndex(), JVNetConst.JVN_RSP_TEXTDATA, false, 0, Consts.TYPE_SET_PARAM, "MobileQuality=1;");
                    if (null != streamPopWindow && streamPopWindow.isShowing())
                    {
                        streamPopWindow.dismiss();
                    }
                    break;
                }

                case R.id.sd: // 标清
                {
                    Jni.sendString(connectChannel.getIndex(), JVNetConst.JVN_RSP_TEXTDATA, false, 0, Consts.TYPE_SET_PARAM, "MobileQuality=2;");
                    if (null != streamPopWindow && streamPopWindow.isShowing())
                    {
                        streamPopWindow.dismiss();
                    }
                    break;
                }

                case R.id.fluent: // 流畅
                {
                    Jni.sendString(connectChannel.getIndex(), JVNetConst.JVN_RSP_TEXTDATA, false, 0, Consts.TYPE_SET_PARAM, "MobileQuality=3;");
                    if (null != streamPopWindow && streamPopWindow.isShowing()) {
                        streamPopWindow.dismiss();
                    }
                    break;
                }

                /** 完成 **/
                case R.id.saveset:
                {
                    Jni.stopRecord(); // 保存当前录像视频
                    recordText.setText(R.string.record);

                    voiceviewText.setText(R.string.voicecall); // 停止语音对话
                    stopVoiceCall(connectChannel.getIndex());
                    connectChannel.setVoiceCall(false);
                    realStop = true;

                    createDialog("请稍等...", false, false); // 创建Dialog

                    wifiSet.setEnabled(true); // 回复无线配置为可点击

                    if ("".equalsIgnoreCase(wifiName.getText().toString().trim())) // 配置
                    {
                        showTextToast(R.string.wifi_name_notnull);
                    }
                    else if ("".equalsIgnoreCase(wifiPass.getText().toString().trim()))
                    {
                        showTextToast(R.string.wifi_pass_notnull);
                    }
                    else
                    {
                        saveWifi();
                        if (View.VISIBLE == wifiSetLayout.getVisibility())
                        {
                            wifiSetLayout.setVisibility(View.GONE);
                            // ytLayout.setVisibility(View.VISIBLE);
                        }
                    }
                    break;
                }

            }
        }
    };

    /**
     * 2015-04-21 修改设备密码
     */
    public void modifypass()
    {
        if (0 == power) {
            return;
        }
        String userName = userET.getText().toString();
        String userPwd = pswET.getText().toString();
        String desUTF8 = descript;
        byte[] paramByte = new byte[Consts.SIZE_ID + Consts.SIZE_PW
                + Consts.SIZE_DESCRIPT];
        byte[] userNameByte = userName.getBytes();
        byte[] userPwdByte = userPwd.getBytes();
        byte[] desByte;
        try {
            desByte = desUTF8.getBytes("GBK"); // 设备端是GBK编码

            System.arraycopy(userNameByte, 0, paramByte, 0, userNameByte.length);
            System.arraycopy(userPwdByte, 0, paramByte, Consts.SIZE_ID, userPwdByte.length);
            System.arraycopy(desByte, 0, paramByte, Consts.SIZE_ID + Consts.SIZE_PW, desByte.length);

            // 2014-12-25 修改设备用户名密码
            // //CALL_TEXT_DATA: 165, 0, 81,
            // {"extend_arg1":58,"extend_arg2":0,"extend_arg3":0,"extend_type":6,"flag":0,"packet_count":4,"packet_id":0,"packet_length":0,"packet_type":6,"type":81}
            Jni.sendSuperBytes(connectChannel.getIndex(), JVNetConst.JVN_RSP_TEXTDATA, true, Consts.RC_EX_ACCOUNT, Consts.EX_ACCOUNT_MODIFY, power, 0, 0, paramByte, paramByte.length);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 保存wifi配置信息
     */
    public void saveWifi() {
        JSONObject newObj = new JSONObject();
        try {
            newObj.put("wifiSsid", wifiName.getText().toString());
            newObj.put("wifiPwd", wifiPass.getText().toString());
            newObj.put("nPacketType", JVNetConst.RC_EXTEND);
            newObj.put("packetCount", JVNetConst.RC_EX_NETWORK);
            newObj.put("nType", JVNetConst.EX_WIFI_AP_CONFIG);
            int[] data = wifiAdmin
                    .getWifiAuthEnc(wifiName.getText().toString());
            newObj.put("wifiAuth", data[0]);
            newObj.put("wifiEncryp", data[1]);
            newObj.put("wifiIndex", 0);
            newObj.put("wifiChannel", 0);
            newObj.put("wifiRate", 0);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

        Jni.setAccessPoint(connectChannel.getIndex(), JVNetConst.JVN_RSP_TEXTDATA, newObj.toString());
//        Log.e("配置wifi请求", newObj.toString());
    }

    /**
     * 开始语音对讲
     */
    public static void startVoiceCall(int index, Channel channel)
    {
        Jni.sendBytes(index, JVNetConst.JVN_REQ_CHAT, new byte[0], 8);
    }

    /**
     * 停止语音对讲
     */
    public static void stopVoiceCall(int index)
    {
        Jni.sendBytes(index, JVNetConst.JVN_CMD_CHATSTOP, new byte[0], 8);
        // 关闭语音对讲
        playAudio.stopPlay();
        playAudio.stopRec();
    }

    /**
     * 单向对讲用功能
     */
    OnTouchListener callOnTouchListener = new OnTouchListener()
    {
        @Override
        public boolean onTouch(View arg0, MotionEvent arg1)
        {

            if (connectChannel.isSingleVoice() && VOICECALLING)
            {
                // 单向对讲
                if (arg1.getAction() == MotionEvent.ACTION_UP
                        || arg1.getAction() == MotionEvent.ACTION_HOVER_MOVE)
                {
                    handler.sendMessage(handler.obtainMessage(AppConsts.STOP_AUDIO_GATHER));

                    new TalkThread(connectChannel.getIndex(), 1).start();
                    VOICECALL_LONG_CLICK = false;
                    // voiceCall.setText(R.string.voice_send);
                    // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
                    voiceTip.setVisibility(View.GONE);
                    handler.sendMessageDelayed(
                            handler.obtainMessage(AppConsts.START_AUDIO_GATHER),
                            2 * 1000);
                }
            }
            return false;
        }

    };

    /**
     * 单向对讲用功能
     */
    OnLongClickListener callOnLongClickListener = new OnLongClickListener()
    {
        @Override
        public boolean onLongClick(View arg0)
        {
            current = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            mAudioManager.setMicrophoneMute(false);
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
            startSendVoice();
            return true;
        }

    };

    /** 开关对讲线程 */
    class TalkThread extends Thread
    {
        private int index = 0;
        private int param = 0;

        TalkThread(int index, int param) {
            this.index = index;
            this.param = param;
        }

        @Override
        public void run() {
            // "talkSwitch=" + tag;// 1开始 0关闭
            for (int i = 0; i < 3; i++) {
                Jni.sendString(index, JVNetConst.JVN_RSP_TEXTDATA, false, 0, AppConsts.TYPE_SET_PARAM,
                               String.format(AppConsts.FORMATTER_TALK_SWITCH, param));
            }
            super.run();
        }

    }

    /**
     * 长按发送语音数据
     */
    private void startSendVoice() {
        if (connectChannel.isSingleVoice() && VOICECALLING) {// 单向对讲且正在对讲
            VOICECALL_LONG_CLICK = true;
            // voiceCall.setText(R.string.voice_stop);

            voiceTip.setVisibility(View.VISIBLE);
            new TalkThread(connectChannel.getIndex(), 0).start();
        }
    }

    /**
     * 码流切换dialog
     */
    public void initStreamPopWindowView()
    {
        // // 获取自定义布局文件pop.xml的视图
        View customView = getLayoutInflater().inflate(R.layout.stream_list,
                null, false);
        // 创建PopupWindow实例,200,150分别是宽度和高度
        streamPopWindow = new PopupWindow(customView, 300, 250);

        /** 在这里可以实现自定义视图的功能 */
        hdBtn = (Button) customView.findViewById(R.id.hd);
        sdBtn = (Button) customView.findViewById(R.id.sd);
        fluentBtn = (Button) customView.findViewById(R.id.fluent);
    }

    /**
     * 特定 json 转 HashMap
     *
     * @return
     */
    public HashMap<String, String> genMsgMap(String msg) {
        HashMap<String, String> map = new HashMap<String, String>();

        if (null == msg || "".equalsIgnoreCase(msg)) {
            return null;
        }
        Matcher matcher = Pattern.compile("([^=;]+)=([^=;]+)").matcher(msg);
        while (matcher.find()) {
            map.put(matcher.group(1), matcher.group(2));
        }
        return map;
    }

    /**
     * 应用层开启音频监听功能
     * 
     * @param index
     * @return
     */
    public static boolean startAudio(int index, int audioByte) {
        boolean open = false;
        if (PlayUtil.isPlayAudio(index)) {// 正在监听,确保不会重复开启
            open = true;
        } else {
            PlayUtil.startAudioMonitor(index);// enable audio
            playAudio.startPlay(audioByte, true);
            open = true;
        }
        return open;
    }

    /**
     * 应用层关闭音频监听功能
     * 
     * @param index
     * @return
     */
    public static boolean stopAudio(int index) {
        boolean close = false;
        if (PlayUtil.isPlayAudio(index)) {// 正在监听，停止监听
            PlayUtil.stopAudioMonitor(index);// stop audio
            playAudio.stopPlay();
            close = true;
        } else {// 确保不会重复关闭
            close = true;
        }
        return close;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        {
            finish();
        }
    }
}
